package com.test.controller;

import com.test.entity.User;
import com.test.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {

    @Autowired
    @Qualifier("loginServiceImpl")
    private LoginService loginService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String id, String passWord, Model model) {
        String pwd = loginService.queryUserPasswordById(id);
        if (pwd == null) {
            model.addAttribute("error", "用户不存在!");
            return "redirect:/login";
        } else if (pwd.equals(passWord)) {
            User user = loginService.queryUserById(id);
            model.addAttribute("user", user);
            return "main";
        } else {
            model.addAttribute("error", "密码错误！");
            return "redirect:/login";
        }
    }

    @PostMapping("/register")
    public String registerUser(User user, Model model) {
        if (loginService.queryUserPasswordById(user.getIdNumber()) == null) {
            model.addAttribute("error", "用户已存在，无法重复注册！");
            return "redirect:/register";
        }
        loginService.registerUser(user);
        return "redirect:/login";
    }



}
